from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs

import webbrowser

from PyPDF2 import PdfReader, PdfWriter
from pathlib import Path
import os
import time
import subprocess

class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
    # 处理 GET 请求
    def do_GET(self):
        # 解析 URL
        parsed_url = urlparse(self.path)
        
        if parsed_url.path == '/shutdown':
            print('服务器关闭...')
            # 关闭服务器
            httpd.shutdown()
        
        # 获取查询参数
        query_params = parse_qs(parsed_url.query)
        
        # 检查是否存在 id 参数
        if 'id' in query_params:
            # 获取 id 参数的值
            id_value = query_params['id'][0]
            # 打印 id 值
            print("收到的 id 值为:", id_value)
        
        # 设置响应状态码为 200
        self.send_response(200)
        # 设置响应头部内容类型为 text/html，并指定字符编码为 UTF-8
        self.send_header('Content-type', 'text/html; charset=utf-8')
        self.end_headers()
        
        # 响应内容为包含上传 PDF 文件的 HTML 页面
        html = """
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <title>Python HTTP Server</title>
        </head>
        <body>
            <h1>上传 PDF 文件</h1>
            <form action="/upload" method="post" enctype="multipart/form-data">
                <input type="file" name="pdf_file">
                <input type="submit" value="上传">
            </form>
            <div onclick="setTimeout(function() {window.close()}, 3000)"><a href="/shutdown">关闭服务器</a></div>
        </body>
        </html>
        """
        self.wfile.write(html.encode(encoding='utf-8'))

    # 处理 POST 请求
    def do_POST(self):
        # 解析 URL
        parsed_url = urlparse(self.path)
        
        # 检查是否为上传文件的请求
        if parsed_url.path == '/upload':
            # 获取 Content-Length
            content_length = int(self.headers['Content-Length'])
            # 读取请求体数据
            post_data = self.rfile.read(content_length)
            current_time_name = time.strftime("%Y_%m_%d--%H_%M_%S", time.localtime())
            file_name = f'{os.getcwd()}\{current_time_name}.pdf'
            # 将文件保存到本地
            with open(file_name, 'wb') as file:
                file.write(post_data)
            
            ####
            
            def pdf_write(func):
                def wrapper(*args, **kwargs):
                    result = func(*args, **kwargs)
                    print(kwargs)
                    out_pdf_path = kwargs['out_pdf_path']
                    current_time = time.strftime("%Y_%m_%d--%H_%M_%S", time.localtime())
                    out_filename = f'{out_pdf_path}/处理后{current_time}.pdf'.replace('/', '\\')
                    with open(out_filename, 'wb') as out:
                        result.write(out)
                    print(out_filename)
                    file_dir = os.path.dirname(out_filename) 
                    subprocess.Popen(['explorer', '/select,', out_filename], cwd=file_dir)
                    subprocess.Popen(['start', '', out_filename], shell=True)
                    
                return wrapper

            @pdf_write
            def split_pdf_Page(start_pageNumber, end_pageNumber, *, pdf_path, out_pdf_path):
                pdf_reader = PdfReader(pdf_path)
                pdf_writer = PdfWriter()

                pdf_pagesNumber = len(pdf_reader.pages)
                if end_pageNumber > pdf_pagesNumber or start_pageNumber > pdf_pagesNumber:
                    return
                for page in range(start_pageNumber, end_pageNumber):
                    pdf_writer.add_page(pdf_reader.pages[page])

                return pdf_writer

            @pdf_write
            def merge_pdf_Page(*, pdf_path_list, out_pdf_path):
                pdf_writer = PdfWriter()
                for pdf_path in pdf_path_list:
                    pdf_reader = PdfReader(pdf_path)
                    pdf_pagesNumber = len(pdf_reader.pages)
                    for page in range(pdf_pagesNumber):
                        pdf_writer.add_page(pdf_reader.pages[page])

                return pdf_writer
            
            split_pdf_Page(0,4,pdf_path=file_name,out_pdf_path='.')
            
            #######
            
            
            
            # 设置响应状态码为 200
            self.send_response(200)
            # 设置响应头部内容类型为 text/plain，并指定字符编码为 UTF-8
            self.send_header('Content-type', 'text/plain; charset=utf-8')
            self.end_headers()
            
            # 响应内容为上传成功消息
            response = "文件上传成功"
            self.wfile.write(response.encode(encoding='utf-8'))
        else:
            # 如果不是上传文件的请求，返回 404 Not Found 错误
            self.send_error(404)

# 设置服务器的 IP 地址和端口
server_address = ('', 8000)
# 创建 HTTP 服务器
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
print('服务器运行中...')
# 在浏览器中打开指定页面

webbrowser.open("http://localhost:8000/")
# 开始监听并处理请求
httpd.serve_forever()
